#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
外观模式 (Facade Pattern) - Python实现详解

外观模式是一种结构设计模式，它为子系统中的一组接口提供一个统一的高层接口。
外观模式定义了一个高层接口，这个接口使得这一子系统更加容易使用。

与Java对比：
1. Python的模块系统天然支持外观模式
2. Python的装饰器可以实现动态外观
3. Python的上下文管理器支持资源管理外观
4. Python的元类可以实现高级外观功能

作者: Assistant
日期: 2024
"""

import time
import logging
import threading
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Callable, Union
from dataclasses import dataclass, field
from enum import Enum
import json
import sqlite3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import hashlib
import os
from contextlib import contextmanager
from functools import wraps


# ============================================================================
# 1. 传统外观模式实现
# ============================================================================

class CPU:
    """
    CPU子系统
    """
    
    def __init__(self):
        self._frequency = 0
        self._temperature = 25
        self._running = False
    
    def start(self) -> None:
        """启动CPU"""
        print("CPU: Starting up...")
        self._running = True
        self._frequency = 3000  # MHz
        self._temperature = 45
        print(f"CPU: Running at {self._frequency}MHz, temperature: {self._temperature}°C")
    
    def stop(self) -> None:
        """停止CPU"""
        print("CPU: Shutting down...")
        self._running = False
        self._frequency = 0
        self._temperature = 25
        print("CPU: Stopped")
    
    def execute(self, instruction: str) -> str:
        """执行指令"""
        if not self._running:
            raise RuntimeError("CPU is not running")
        
        print(f"CPU: Executing instruction '{instruction}'")
        self._temperature += 2  # 执行指令会增加温度
        return f"Executed: {instruction}"
    
    def get_status(self) -> Dict[str, Any]:
        """获取CPU状态"""
        return {
            "running": self._running,
            "frequency": self._frequency,
            "temperature": self._temperature
        }


class Memory:
    """
    内存子系统
    """
    
    def __init__(self, size_gb: int = 8):
        self._size_gb = size_gb
        self._used_mb = 0
        self._data = {}
        self._initialized = False
    
    def initialize(self) -> None:
        """初始化内存"""
        print(f"Memory: Initializing {self._size_gb}GB memory...")
        self._initialized = True
        self._used_mb = 100  # 系统占用
        print(f"Memory: Initialized, {self._used_mb}MB used")
    
    def cleanup(self) -> None:
        """清理内存"""
        print("Memory: Cleaning up...")
        self._data.clear()
        self._used_mb = 0
        self._initialized = False
        print("Memory: Cleaned up")
    
    def allocate(self, size_mb: int, name: str) -> bool:
        """分配内存"""
        if not self._initialized:
            raise RuntimeError("Memory is not initialized")
        
        available_mb = (self._size_gb * 1024) - self._used_mb
        if size_mb > available_mb:
            print(f"Memory: Failed to allocate {size_mb}MB for '{name}' - insufficient memory")
            return False
        
        self._data[name] = size_mb
        self._used_mb += size_mb
        print(f"Memory: Allocated {size_mb}MB for '{name}', total used: {self._used_mb}MB")
        return True
    
    def deallocate(self, name: str) -> bool:
        """释放内存"""
        if name in self._data:
            size_mb = self._data.pop(name)
            self._used_mb -= size_mb
            print(f"Memory: Deallocated {size_mb}MB for '{name}', total used: {self._used_mb}MB")
            return True
        
        print(f"Memory: No allocation found for '{name}'")
        return False
    
    def get_status(self) -> Dict[str, Any]:
        """获取内存状态"""
        return {
            "initialized": self._initialized,
            "total_gb": self._size_gb,
            "used_mb": self._used_mb,
            "available_mb": (self._size_gb * 1024) - self._used_mb,
            "allocations": self._data.copy()
        }


class Storage:
    """
    存储子系统
    """
    
    def __init__(self, capacity_gb: int = 500):
        self._capacity_gb = capacity_gb
        self._used_gb = 0
        self._files = {}
        self._mounted = False
    
    def mount(self) -> None:
        """挂载存储"""
        print(f"Storage: Mounting {self._capacity_gb}GB storage...")
        self._mounted = True
        self._used_gb = 10  # 系统文件占用
        print(f"Storage: Mounted, {self._used_gb}GB used")
    
    def unmount(self) -> None:
        """卸载存储"""
        print("Storage: Unmounting...")
        self._files.clear()
        self._used_gb = 0
        self._mounted = False
        print("Storage: Unmounted")
    
    def write_file(self, filename: str, size_mb: int) -> bool:
        """写入文件"""
        if not self._mounted:
            raise RuntimeError("Storage is not mounted")
        
        size_gb = size_mb / 1024
        available_gb = self._capacity_gb - self._used_gb
        
        if size_gb > available_gb:
            print(f"Storage: Failed to write '{filename}' ({size_mb}MB) - insufficient space")
            return False
        
        self._files[filename] = size_mb
        self._used_gb += size_gb
        print(f"Storage: Wrote '{filename}' ({size_mb}MB), total used: {self._used_gb:.2f}GB")
        return True
    
    def read_file(self, filename: str) -> Optional[int]:
        """读取文件"""
        if not self._mounted:
            raise RuntimeError("Storage is not mounted")
        
        if filename in self._files:
            size_mb = self._files[filename]
            print(f"Storage: Read '{filename}' ({size_mb}MB)")
            return size_mb
        
        print(f"Storage: File '{filename}' not found")
        return None
    
    def delete_file(self, filename: str) -> bool:
        """删除文件"""
        if filename in self._files:
            size_mb = self._files.pop(filename)
            size_gb = size_mb / 1024
            self._used_gb -= size_gb
            print(f"Storage: Deleted '{filename}' ({size_mb}MB), total used: {self._used_gb:.2f}GB")
            return True
        
        print(f"Storage: File '{filename}' not found")
        return False
    
    def get_status(self) -> Dict[str, Any]:
        """获取存储状态"""
        return {
            "mounted": self._mounted,
            "capacity_gb": self._capacity_gb,
            "used_gb": round(self._used_gb, 2),
            "available_gb": round(self._capacity_gb - self._used_gb, 2),
            "files": self._files.copy()
        }


class Network:
    """
    网络子系统
    """
    
    def __init__(self):
        self._connected = False
        self._ip_address = ""
        self._bandwidth_mbps = 0
        self._packets_sent = 0
        self._packets_received = 0
    
    def connect(self, ip_address: str = "192.168.1.100") -> None:
        """连接网络"""
        print(f"Network: Connecting to network...")
        self._connected = True
        self._ip_address = ip_address
        self._bandwidth_mbps = 100
        print(f"Network: Connected with IP {self._ip_address}, bandwidth: {self._bandwidth_mbps}Mbps")
    
    def disconnect(self) -> None:
        """断开网络"""
        print("Network: Disconnecting...")
        self._connected = False
        self._ip_address = ""
        self._bandwidth_mbps = 0
        print("Network: Disconnected")
    
    def send_data(self, data: str, destination: str) -> bool:
        """发送数据"""
        if not self._connected:
            print("Network: Cannot send data - not connected")
            return False
        
        self._packets_sent += 1
        print(f"Network: Sent data to {destination}: '{data[:50]}{'...' if len(data) > 50 else ''}'")
        return True
    
    def receive_data(self, source: str) -> str:
        """接收数据"""
        if not self._connected:
            print("Network: Cannot receive data - not connected")
            return ""
        
        self._packets_received += 1
        data = f"Response from {source} at {time.strftime('%H:%M:%S')}"
        print(f"Network: Received data from {source}: '{data}'")
        return data
    
    def get_status(self) -> Dict[str, Any]:
        """获取网络状态"""
        return {
            "connected": self._connected,
            "ip_address": self._ip_address,
            "bandwidth_mbps": self._bandwidth_mbps,
            "packets_sent": self._packets_sent,
            "packets_received": self._packets_received
        }


class ComputerFacade:
    """
    计算机外观类
    提供简化的接口来操作复杂的计算机子系统
    """
    
    def __init__(self):
        self._cpu = CPU()
        self._memory = Memory()
        self._storage = Storage()
        self._network = Network()
        self._running = False
    
    def start_computer(self) -> None:
        """启动计算机（简化接口）"""
        print("\n=== Starting Computer ===")
        
        try:
            # 按顺序启动各个子系统
            self._cpu.start()
            self._memory.initialize()
            self._storage.mount()
            self._network.connect()
            
            self._running = True
            print("Computer: Successfully started!")
            
        except Exception as e:
            print(f"Computer: Failed to start - {e}")
            self.shutdown_computer()
    
    def shutdown_computer(self) -> None:
        """关闭计算机（简化接口）"""
        print("\n=== Shutting Down Computer ===")
        
        try:
            # 按相反顺序关闭各个子系统
            self._network.disconnect()
            self._storage.unmount()
            self._memory.cleanup()
            self._cpu.stop()
            
            self._running = False
            print("Computer: Successfully shut down!")
            
        except Exception as e:
            print(f"Computer: Error during shutdown - {e}")
    
    def run_program(self, program_name: str, memory_mb: int = 100, 
                   storage_mb: int = 50) -> bool:
        """运行程序（简化接口）"""
        if not self._running:
            print("Computer: Cannot run program - computer is not running")
            return False
        
        print(f"\n=== Running Program: {program_name} ===")
        
        try:
            # 分配内存
            if not self._memory.allocate(memory_mb, program_name):
                return False
            
            # 创建程序文件
            if not self._storage.write_file(f"{program_name}.exe", storage_mb):
                self._memory.deallocate(program_name)
                return False
            
            # 执行程序
            result = self._cpu.execute(f"run {program_name}")
            
            # 模拟网络通信
            self._network.send_data(f"Program {program_name} started", "server")
            response = self._network.receive_data("server")
            
            print(f"Computer: Program '{program_name}' is running successfully")
            return True
            
        except Exception as e:
            print(f"Computer: Failed to run program '{program_name}' - {e}")
            self._memory.deallocate(program_name)
            return False
    
    def stop_program(self, program_name: str) -> bool:
        """停止程序（简化接口）"""
        if not self._running:
            print("Computer: Cannot stop program - computer is not running")
            return False
        
        print(f"\n=== Stopping Program: {program_name} ===")
        
        try:
            # 释放内存
            memory_freed = self._memory.deallocate(program_name)
            
            # 删除程序文件（可选）
            file_deleted = self._storage.delete_file(f"{program_name}.exe")
            
            # 通知网络
            self._network.send_data(f"Program {program_name} stopped", "server")
            
            if memory_freed:
                print(f"Computer: Program '{program_name}' stopped successfully")
                return True
            else:
                print(f"Computer: Program '{program_name}' was not running")
                return False
                
        except Exception as e:
            print(f"Computer: Error stopping program '{program_name}' - {e}")
            return False
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态（简化接口）"""
        return {
            "computer_running": self._running,
            "cpu": self._cpu.get_status(),
            "memory": self._memory.get_status(),
            "storage": self._storage.get_status(),
            "network": self._network.get_status()
        }
    
    def install_software(self, software_name: str, size_mb: int) -> bool:
        """安装软件（简化接口）"""
        if not self._running:
            print("Computer: Cannot install software - computer is not running")
            return False
        
        print(f"\n=== Installing Software: {software_name} ===")
        
        try:
            # 下载软件
            self._network.send_data(f"Download {software_name}", "download_server")
            download_data = self._network.receive_data("download_server")
            
            # 分配临时内存
            temp_memory = size_mb // 2
            if not self._memory.allocate(temp_memory, f"temp_{software_name}"):
                return False
            
            # 写入存储
            if not self._storage.write_file(f"{software_name}_installer.exe", size_mb):
                self._memory.deallocate(f"temp_{software_name}")
                return False
            
            # 执行安装
            self._cpu.execute(f"install {software_name}")
            
            # 清理临时文件
            self._memory.deallocate(f"temp_{software_name}")
            self._storage.delete_file(f"{software_name}_installer.exe")
            
            # 创建已安装软件记录
            self._storage.write_file(f"{software_name}.app", size_mb)
            
            print(f"Computer: Software '{software_name}' installed successfully")
            return True
            
        except Exception as e:
            print(f"Computer: Failed to install software '{software_name}' - {e}")
            return False
    
    def backup_data(self, backup_name: str) -> bool:
        """备份数据（简化接口）"""
        if not self._running:
            print("Computer: Cannot backup data - computer is not running")
            return False
        
        print(f"\n=== Backing Up Data: {backup_name} ===")
        
        try:
            # 计算备份大小
            storage_status = self._storage.get_status()
            backup_size_mb = int(storage_status['used_gb'] * 1024 * 0.8)  # 80%的数据
            
            # 分配内存用于备份操作
            if not self._memory.allocate(200, f"backup_{backup_name}"):
                return False
            
            # 执行备份
            self._cpu.execute(f"backup data to {backup_name}")
            
            # 创建备份文件
            if not self._storage.write_file(f"{backup_name}.backup", backup_size_mb):
                self._memory.deallocate(f"backup_{backup_name}")
                return False
            
            # 上传到网络
            self._network.send_data(f"Backup {backup_name} completed", "backup_server")
            
            # 清理
            self._memory.deallocate(f"backup_{backup_name}")
            
            print(f"Computer: Data backed up successfully as '{backup_name}'")
            return True
            
        except Exception as e:
            print(f"Computer: Failed to backup data - {e}")
            return False
    
    def is_running(self) -> bool:
        """检查计算机是否运行"""
        return self._running


# ============================================================================
# 2. 数据库外观模式
# ============================================================================

class DatabaseConnection:
    """
    数据库连接子系统
    """
    
    def __init__(self, db_path: str = ":memory:"):
        self._db_path = db_path
        self._connection: Optional[sqlite3.Connection] = None
        self._cursor: Optional[sqlite3.Cursor] = None
    
    def connect(self) -> bool:
        """连接数据库"""
        try:
            self._connection = sqlite3.connect(self._db_path)
            self._cursor = self._connection.cursor()
            print(f"Database: Connected to {self._db_path}")
            return True
        except Exception as e:
            print(f"Database: Connection failed - {e}")
            return False
    
    def disconnect(self) -> None:
        """断开数据库连接"""
        if self._cursor:
            self._cursor.close()
        if self._connection:
            self._connection.close()
        print("Database: Disconnected")
    
    def execute(self, query: str, params: tuple = ()) -> List[tuple]:
        """执行SQL查询"""
        if not self._cursor:
            raise RuntimeError("Database not connected")
        
        try:
            self._cursor.execute(query, params)
            if query.strip().upper().startswith('SELECT'):
                return self._cursor.fetchall()
            else:
                self._connection.commit()
                return []
        except Exception as e:
            print(f"Database: Query execution failed - {e}")
            raise
    
    def get_table_info(self, table_name: str) -> List[tuple]:
        """获取表信息"""
        return self.execute(f"PRAGMA table_info({table_name})")


class QueryBuilder:
    """
    查询构建器子系统
    """
    
    @staticmethod
    def create_table(table_name: str, columns: Dict[str, str]) -> str:
        """创建表的SQL"""
        column_defs = [f"{name} {type_}" for name, type_ in columns.items()]
        return f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join(column_defs)})"
    
    @staticmethod
    def insert(table_name: str, data: Dict[str, Any]) -> tuple:
        """插入数据的SQL"""
        columns = ', '.join(data.keys())
        placeholders = ', '.join(['?' for _ in data])
        query = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
        return query, tuple(data.values())
    
    @staticmethod
    def select(table_name: str, columns: List[str] = None, 
              where: Dict[str, Any] = None, order_by: str = None, 
              limit: int = None) -> tuple:
        """查询数据的SQL"""
        # 构建SELECT子句
        if columns:
            select_clause = ', '.join(columns)
        else:
            select_clause = '*'
        
        query = f"SELECT {select_clause} FROM {table_name}"
        params = []
        
        # 构建WHERE子句
        if where:
            conditions = []
            for key, value in where.items():
                conditions.append(f"{key} = ?")
                params.append(value)
            query += f" WHERE {' AND '.join(conditions)}"
        
        # 构建ORDER BY子句
        if order_by:
            query += f" ORDER BY {order_by}"
        
        # 构建LIMIT子句
        if limit:
            query += f" LIMIT {limit}"
        
        return query, tuple(params)
    
    @staticmethod
    def update(table_name: str, data: Dict[str, Any], 
              where: Dict[str, Any]) -> tuple:
        """更新数据的SQL"""
        set_clause = ', '.join([f"{key} = ?" for key in data.keys()])
        where_clause = ' AND '.join([f"{key} = ?" for key in where.keys()])
        
        query = f"UPDATE {table_name} SET {set_clause} WHERE {where_clause}"
        params = list(data.values()) + list(where.values())
        
        return query, tuple(params)
    
    @staticmethod
    def delete(table_name: str, where: Dict[str, Any]) -> tuple:
        """删除数据的SQL"""
        where_clause = ' AND '.join([f"{key} = ?" for key in where.keys()])
        query = f"DELETE FROM {table_name} WHERE {where_clause}"
        return query, tuple(where.values())


class DataValidator:
    """
    数据验证子系统
    """
    
    @staticmethod
    def validate_email(email: str) -> bool:
        """验证邮箱格式"""
        import re
        pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
        return bool(re.match(pattern, email))
    
    @staticmethod
    def validate_phone(phone: str) -> bool:
        """验证电话号码格式"""
        import re
        pattern = r'^\+?1?\d{9,15}$'
        return bool(re.match(pattern, phone.replace('-', '').replace(' ', '')))
    
    @staticmethod
    def validate_required_fields(data: Dict[str, Any], 
                               required_fields: List[str]) -> List[str]:
        """验证必填字段"""
        missing_fields = []
        for field in required_fields:
            if field not in data or not data[field]:
                missing_fields.append(field)
        return missing_fields
    
    @staticmethod
    def sanitize_string(value: str) -> str:
        """清理字符串"""
        if not isinstance(value, str):
            return str(value)
        # 移除潜在的SQL注入字符
        dangerous_chars = ["'", '"', ';', '--', '/*', '*/', 'xp_', 'sp_']
        sanitized = value
        for char in dangerous_chars:
            sanitized = sanitized.replace(char, '')
        return sanitized.strip()


class CacheManager:
    """
    缓存管理子系统
    """
    
    def __init__(self, max_size: int = 100):
        self._cache: Dict[str, Any] = {}
        self._access_times: Dict[str, float] = {}
        self._max_size = max_size
    
    def get(self, key: str) -> Optional[Any]:
        """获取缓存"""
        if key in self._cache:
            self._access_times[key] = time.time()
            print(f"Cache: Hit for key '{key}'")
            return self._cache[key]
        
        print(f"Cache: Miss for key '{key}'")
        return None
    
    def set(self, key: str, value: Any) -> None:
        """设置缓存"""
        if len(self._cache) >= self._max_size:
            self._evict_oldest()
        
        self._cache[key] = value
        self._access_times[key] = time.time()
        print(f"Cache: Set key '{key}'")
    
    def _evict_oldest(self) -> None:
        """淘汰最旧的缓存项"""
        if not self._access_times:
            return
        
        oldest_key = min(self._access_times.keys(), 
                        key=lambda k: self._access_times[k])
        del self._cache[oldest_key]
        del self._access_times[oldest_key]
        print(f"Cache: Evicted oldest key '{oldest_key}'")
    
    def clear(self) -> None:
        """清空缓存"""
        self._cache.clear()
        self._access_times.clear()
        print("Cache: Cleared all entries")
    
    def get_stats(self) -> Dict[str, Any]:
        """获取缓存统计"""
        return {
            "size": len(self._cache),
            "max_size": self._max_size,
            "keys": list(self._cache.keys())
        }


class DatabaseFacade:
    """
    数据库外观类
    提供简化的数据库操作接口
    """
    
    def __init__(self, db_path: str = ":memory:"):
        self._db = DatabaseConnection(db_path)
        self._query_builder = QueryBuilder()
        self._validator = DataValidator()
        self._cache = CacheManager()
        self._connected = False
    
    def connect(self) -> bool:
        """连接数据库"""
        if self._db.connect():
            self._connected = True
            return True
        return False
    
    def disconnect(self) -> None:
        """断开连接"""
        self._db.disconnect()
        self._cache.clear()
        self._connected = False
    
    def create_user_table(self) -> bool:
        """创建用户表（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return False
        
        try:
            columns = {
                'id': 'INTEGER PRIMARY KEY AUTOINCREMENT',
                'name': 'TEXT NOT NULL',
                'email': 'TEXT UNIQUE NOT NULL',
                'phone': 'TEXT',
                'created_at': 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'
            }
            
            query = self._query_builder.create_table('users', columns)
            self._db.execute(query)
            print("DatabaseFacade: User table created successfully")
            return True
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to create user table - {e}")
            return False
    
    def add_user(self, name: str, email: str, phone: str = None) -> bool:
        """添加用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return False
        
        # 数据验证
        user_data = {'name': name, 'email': email}
        if phone:
            user_data['phone'] = phone
        
        # 验证必填字段
        missing_fields = self._validator.validate_required_fields(
            user_data, ['name', 'email']
        )
        if missing_fields:
            print(f"DatabaseFacade: Missing required fields: {missing_fields}")
            return False
        
        # 验证邮箱格式
        if not self._validator.validate_email(email):
            print(f"DatabaseFacade: Invalid email format: {email}")
            return False
        
        # 验证电话号码格式（如果提供）
        if phone and not self._validator.validate_phone(phone):
            print(f"DatabaseFacade: Invalid phone format: {phone}")
            return False
        
        # 清理数据
        clean_data = {
            'name': self._validator.sanitize_string(name),
            'email': self._validator.sanitize_string(email)
        }
        if phone:
            clean_data['phone'] = self._validator.sanitize_string(phone)
        
        try:
            query, params = self._query_builder.insert('users', clean_data)
            self._db.execute(query, params)
            
            # 清除相关缓存
            self._cache.clear()
            
            print(f"DatabaseFacade: User '{name}' added successfully")
            return True
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to add user - {e}")
            return False
    
    def get_user_by_email(self, email: str) -> Optional[Dict[str, Any]]:
        """根据邮箱获取用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return None
        
        # 检查缓存
        cache_key = f"user_email_{email}"
        cached_user = self._cache.get(cache_key)
        if cached_user:
            return cached_user
        
        try:
            query, params = self._query_builder.select(
                'users', 
                where={'email': email}
            )
            
            results = self._db.execute(query, params)
            
            if results:
                user_data = {
                    'id': results[0][0],
                    'name': results[0][1],
                    'email': results[0][2],
                    'phone': results[0][3],
                    'created_at': results[0][4]
                }
                
                # 缓存结果
                self._cache.set(cache_key, user_data)
                
                print(f"DatabaseFacade: Found user with email '{email}'")
                return user_data
            else:
                print(f"DatabaseFacade: No user found with email '{email}'")
                return None
                
        except Exception as e:
            print(f"DatabaseFacade: Failed to get user - {e}")
            return None
    
    def get_all_users(self, limit: int = None) -> List[Dict[str, Any]]:
        """获取所有用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return []
        
        # 检查缓存
        cache_key = f"all_users_limit_{limit}"
        cached_users = self._cache.get(cache_key)
        if cached_users:
            return cached_users
        
        try:
            query, params = self._query_builder.select(
                'users',
                order_by='created_at DESC',
                limit=limit
            )
            
            results = self._db.execute(query, params)
            
            users = []
            for row in results:
                user_data = {
                    'id': row[0],
                    'name': row[1],
                    'email': row[2],
                    'phone': row[3],
                    'created_at': row[4]
                }
                users.append(user_data)
            
            # 缓存结果
            self._cache.set(cache_key, users)
            
            print(f"DatabaseFacade: Retrieved {len(users)} users")
            return users
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to get users - {e}")
            return []
    
    def update_user(self, user_id: int, **kwargs) -> bool:
        """更新用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return False
        
        if not kwargs:
            print("DatabaseFacade: No data provided for update")
            return False
        
        # 验证数据
        if 'email' in kwargs and not self._validator.validate_email(kwargs['email']):
            print(f"DatabaseFacade: Invalid email format: {kwargs['email']}")
            return False
        
        if 'phone' in kwargs and not self._validator.validate_phone(kwargs['phone']):
            print(f"DatabaseFacade: Invalid phone format: {kwargs['phone']}")
            return False
        
        # 清理数据
        clean_data = {}
        for key, value in kwargs.items():
            if isinstance(value, str):
                clean_data[key] = self._validator.sanitize_string(value)
            else:
                clean_data[key] = value
        
        try:
            query, params = self._query_builder.update(
                'users', 
                clean_data, 
                {'id': user_id}
            )
            
            self._db.execute(query, params)
            
            # 清除相关缓存
            self._cache.clear()
            
            print(f"DatabaseFacade: User {user_id} updated successfully")
            return True
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to update user - {e}")
            return False
    
    def delete_user(self, user_id: int) -> bool:
        """删除用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return False
        
        try:
            query, params = self._query_builder.delete('users', {'id': user_id})
            self._db.execute(query, params)
            
            # 清除相关缓存
            self._cache.clear()
            
            print(f"DatabaseFacade: User {user_id} deleted successfully")
            return True
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to delete user - {e}")
            return False
    
    def search_users(self, keyword: str) -> List[Dict[str, Any]]:
        """搜索用户（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return []
        
        # 检查缓存
        cache_key = f"search_{keyword}"
        cached_results = self._cache.get(cache_key)
        if cached_results:
            return cached_results
        
        try:
            # 使用LIKE查询搜索名称和邮箱
            query = """
                SELECT id, name, email, phone, created_at 
                FROM users 
                WHERE name LIKE ? OR email LIKE ?
                ORDER BY name
            """
            
            search_term = f"%{keyword}%"
            results = self._db.execute(query, (search_term, search_term))
            
            users = []
            for row in results:
                user_data = {
                    'id': row[0],
                    'name': row[1],
                    'email': row[2],
                    'phone': row[3],
                    'created_at': row[4]
                }
                users.append(user_data)
            
            # 缓存结果
            self._cache.set(cache_key, users)
            
            print(f"DatabaseFacade: Found {len(users)} users matching '{keyword}'")
            return users
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to search users - {e}")
            return []
    
    def get_user_count(self) -> int:
        """获取用户总数（简化接口）"""
        if not self._connected:
            print("DatabaseFacade: Not connected to database")
            return 0
        
        try:
            results = self._db.execute("SELECT COUNT(*) FROM users")
            count = results[0][0] if results else 0
            print(f"DatabaseFacade: Total users: {count}")
            return count
            
        except Exception as e:
            print(f"DatabaseFacade: Failed to get user count - {e}")
            return 0
    
    def get_cache_stats(self) -> Dict[str, Any]:
        """获取缓存统计"""
        return self._cache.get_stats()


# ============================================================================
# 3. 邮件系统外观模式
# ============================================================================

class EmailConfig:
    """
    邮件配置子系统
    """
    
    def __init__(self):
        self._smtp_server = ""
        self._smtp_port = 587
        self._username = ""
        self._password = ""
        self._use_tls = True
        self._timeout = 30
    
    def set_smtp_config(self, server: str, port: int = 587, 
                       use_tls: bool = True, timeout: int = 30) -> None:
        """设置SMTP配置"""
        self._smtp_server = server
        self._smtp_port = port
        self._use_tls = use_tls
        self._timeout = timeout
        print(f"EmailConfig: SMTP configured - {server}:{port}")
    
    def set_credentials(self, username: str, password: str) -> None:
        """设置认证信息"""
        self._username = username
        self._password = password
        print(f"EmailConfig: Credentials set for {username}")
    
    def get_config(self) -> Dict[str, Any]:
        """获取配置"""
        return {
            'smtp_server': self._smtp_server,
            'smtp_port': self._smtp_port,
            'username': self._username,
            'use_tls': self._use_tls,
            'timeout': self._timeout
        }
    
    def is_configured(self) -> bool:
        """检查是否已配置"""
        return bool(self._smtp_server and self._username and self._password)


class EmailTemplate:
    """
    邮件模板子系统
    """
    
    def __init__(self):
        self._templates = {
            'welcome': {
                'subject': 'Welcome to {company_name}!',
                'body': '''
                    Dear {user_name},
                    
                    Welcome to {company_name}! We're excited to have you on board.
                    
                    Your account has been successfully created with the email: {user_email}
                    
                    Best regards,
                    The {company_name} Team
                '''
            },
            'password_reset': {
                'subject': 'Password Reset Request',
                'body': '''
                    Dear {user_name},
                    
                    You have requested to reset your password. Please click the link below:
                    
                    {reset_link}
                    
                    This link will expire in 24 hours.
                    
                    If you didn't request this, please ignore this email.
                    
                    Best regards,
                    Security Team
                '''
            },
            'notification': {
                'subject': 'Notification: {notification_type}',
                'body': '''
                    Dear {user_name},
                    
                    {notification_message}
                    
                    Time: {timestamp}
                    
                    Best regards,
                    System Notifications
                '''
            }
        }
    
    def get_template(self, template_name: str) -> Optional[Dict[str, str]]:
        """获取模板"""
        return self._templates.get(template_name)
    
    def render_template(self, template_name: str, **kwargs) -> Optional[Dict[str, str]]:
        """渲染模板"""
        template = self.get_template(template_name)
        if not template:
            print(f"EmailTemplate: Template '{template_name}' not found")
            return None
        
        try:
            rendered = {
                'subject': template['subject'].format(**kwargs),
                'body': template['body'].format(**kwargs)
            }
            print(f"EmailTemplate: Template '{template_name}' rendered successfully")
            return rendered
        except KeyError as e:
            print(f"EmailTemplate: Missing template variable: {e}")
            return None
    
    def add_template(self, name: str, subject: str, body: str) -> None:
        """添加模板"""
        self._templates[name] = {
            'subject': subject,
            'body': body
        }
        print(f"EmailTemplate: Template '{name}' added")
    
    def list_templates(self) -> List[str]:
        """列出所有模板"""
        return list(self._templates.keys())


class EmailSender:
    """
    邮件发送子系统
    """
    
    def __init__(self):
        self._sent_count = 0
        self._failed_count = 0
    
    def send_email(self, config: Dict[str, Any], to_email: str, 
                  subject: str, body: str, from_email: str = None) -> bool:
        """发送邮件"""
        try:
            # 模拟邮件发送（实际应用中会使用真实的SMTP）
            print(f"EmailSender: Connecting to {config['smtp_server']}:{config['smtp_port']}")
            
            # 模拟认证
            print(f"EmailSender: Authenticating as {config['username']}")
            
            # 模拟发送
            from_addr = from_email or config['username']
            print(f"EmailSender: Sending email")
            print(f"  From: {from_addr}")
            print(f"  To: {to_email}")
            print(f"  Subject: {subject}")
            print(f"  Body length: {len(body)} characters")
            
            # 模拟发送延迟
            time.sleep(0.1)
            
            self._sent_count += 1
            print(f"EmailSender: Email sent successfully")
            return True
            
        except Exception as e:
            self._failed_count += 1
            print(f"EmailSender: Failed to send email - {e}")
            return False
    
    def send_bulk_email(self, config: Dict[str, Any], recipients: List[str],
                       subject: str, body: str, from_email: str = None) -> Dict[str, int]:
        """批量发送邮件"""
        results = {'sent': 0, 'failed': 0}
        
        print(f"EmailSender: Starting bulk email to {len(recipients)} recipients")
        
        for recipient in recipients:
            if self.send_email(config, recipient, subject, body, from_email):
                results['sent'] += 1
            else:
                results['failed'] += 1
        
        print(f"EmailSender: Bulk email completed - {results['sent']} sent, {results['failed']} failed")
        return results
    
    def get_stats(self) -> Dict[str, int]:
        """获取发送统计"""
        return {
            'sent_count': self._sent_count,
            'failed_count': self._failed_count
        }


class EmailLogger:
    """
    邮件日志子系统
    """
    
    def __init__(self):
        self._logs = []
        self._max_logs = 1000
    
    def log_email(self, to_email: str, subject: str, status: str, 
                 timestamp: float = None) -> None:
        """记录邮件日志"""
        log_entry = {
            'timestamp': timestamp or time.time(),
            'to_email': to_email,
            'subject': subject,
            'status': status
        }
        
        self._logs.append(log_entry)
        
        # 保持日志数量在限制内
        if len(self._logs) > self._max_logs:
            self._logs = self._logs[-self._max_logs:]
        
        print(f"EmailLogger: Logged email to {to_email} - {status}")
    
    def get_recent_logs(self, count: int = 10) -> List[Dict[str, Any]]:
        """获取最近的日志"""
        return self._logs[-count:] if self._logs else []
    
    def get_logs_by_status(self, status: str) -> List[Dict[str, Any]]:
        """根据状态获取日志"""
        return [log for log in self._logs if log['status'] == status]
    
    def get_log_stats(self) -> Dict[str, int]:
        """获取日志统计"""
        stats = {'total': len(self._logs)}
        
        for log in self._logs:
            status = log['status']
            stats[status] = stats.get(status, 0) + 1
        
        return stats
    
    def clear_logs(self) -> None:
        """清空日志"""
        self._logs.clear()
        print("EmailLogger: Logs cleared")


class EmailFacade:
    """
    邮件系统外观类
    提供简化的邮件操作接口
    """
    
    def __init__(self):
        self._config = EmailConfig()
        self._template = EmailTemplate()
        self._sender = EmailSender()
        self._logger = EmailLogger()
    
    def setup_email_server(self, smtp_server: str, smtp_port: int = 587,
                          username: str = "", password: str = "",
                          use_tls: bool = True) -> None:
        """设置邮件服务器（简化接口）"""
        print("\n=== Setting up Email Server ===")
        
        self._config.set_smtp_config(smtp_server, smtp_port, use_tls)
        if username and password:
            self._config.set_credentials(username, password)
        
        print("EmailFacade: Email server setup completed")
    
    def send_welcome_email(self, user_name: str, user_email: str, 
                          company_name: str = "Our Company") -> bool:
        """发送欢迎邮件（简化接口）"""
        if not self._config.is_configured():
            print("EmailFacade: Email server not configured")
            return False
        
        print(f"\n=== Sending Welcome Email to {user_name} ===")
        
        # 渲染模板
        rendered = self._template.render_template(
            'welcome',
            user_name=user_name,
            user_email=user_email,
            company_name=company_name
        )
        
        if not rendered:
            return False
        
        # 发送邮件
        config = self._config.get_config()
        success = self._sender.send_email(
            config, user_email, rendered['subject'], rendered['body']
        )
        
        # 记录日志
        self._logger.log_email(
            user_email, rendered['subject'], 
            'sent' if success else 'failed'
        )
        
        return success
    
    def send_password_reset_email(self, user_name: str, user_email: str,
                                 reset_link: str) -> bool:
        """发送密码重置邮件（简化接口）"""
        if not self._config.is_configured():
            print("EmailFacade: Email server not configured")
            return False
        
        print(f"\n=== Sending Password Reset Email to {user_name} ===")
        
        # 渲染模板
        rendered = self._template.render_template(
            'password_reset',
            user_name=user_name,
            reset_link=reset_link
        )
        
        if not rendered:
            return False
        
        # 发送邮件
        config = self._config.get_config()
        success = self._sender.send_email(
            config, user_email, rendered['subject'], rendered['body']
        )
        
        # 记录日志
        self._logger.log_email(
            user_email, rendered['subject'],
            'sent' if success else 'failed'
        )
        
        return success
    
    def send_notification_email(self, user_name: str, user_email: str,
                               notification_type: str, message: str) -> bool:
        """发送通知邮件（简化接口）"""
        if not self._config.is_configured():
            print("EmailFacade: Email server not configured")
            return False
        
        print(f"\n=== Sending Notification Email to {user_name} ===")
        
        # 渲染模板
        rendered = self._template.render_template(
            'notification',
            user_name=user_name,
            notification_type=notification_type,
            notification_message=message,
            timestamp=time.strftime('%Y-%m-%d %H:%M:%S')
        )
        
        if not rendered:
            return False
        
        # 发送邮件
        config = self._config.get_config()
        success = self._sender.send_email(
            config, user_email, rendered['subject'], rendered['body']
        )
        
        # 记录日志
        self._logger.log_email(
            user_email, rendered['subject'],
            'sent' if success else 'failed'
        )
        
        return success
    
    def send_custom_email(self, to_email: str, subject: str, body: str,
                         from_email: str = None) -> bool:
        """发送自定义邮件（简化接口）"""
        if not self._config.is_configured():
            print("EmailFacade: Email server not configured")
            return False
        
        print(f"\n=== Sending Custom Email ===")
        
        # 发送邮件
        config = self._config.get_config()
        success = self._sender.send_email(
            config, to_email, subject, body, from_email
        )
        
        # 记录日志
        self._logger.log_email(
            to_email, subject,
            'sent' if success else 'failed'
        )
        
        return success
    
    def send_bulk_notification(self, recipients: List[str], 
                              notification_type: str, message: str) -> Dict[str, int]:
        """批量发送通知（简化接口）"""
        if not self._config.is_configured():
            print("EmailFacade: Email server not configured")
            return {'sent': 0, 'failed': len(recipients)}
        
        print(f"\n=== Sending Bulk Notification to {len(recipients)} recipients ===")
        
        # 渲染模板
        rendered = self._template.render_template(
            'notification',
            user_name='Valued User',  # 通用称呼
            notification_type=notification_type,
            notification_message=message,
            timestamp=time.strftime('%Y-%m-%d %H:%M:%S')
        )
        
        if not rendered:
            return {'sent': 0, 'failed': len(recipients)}
        
        # 批量发送
        config = self._config.get_config()
        results = self._sender.send_bulk_email(
            config, recipients, rendered['subject'], rendered['body']
        )
        
        # 批量记录日志
        for recipient in recipients:
            status = 'sent' if results['sent'] > 0 else 'failed'
            self._logger.log_email(recipient, rendered['subject'], status)
        
        return results
    
    def get_email_stats(self) -> Dict[str, Any]:
        """获取邮件统计（简化接口）"""
        sender_stats = self._sender.get_stats()
        logger_stats = self._logger.get_log_stats()
        
        return {
            'sender_stats': sender_stats,
            'log_stats': logger_stats,
            'configured': self._config.is_configured(),
            'available_templates': self._template.list_templates()
        }
    
    def get_recent_email_logs(self, count: int = 10) -> List[Dict[str, Any]]:
        """获取最近的邮件日志（简化接口）"""
        logs = self._logger.get_recent_logs(count)
        
        # 格式化时间戳
        for log in logs:
            log['formatted_time'] = time.strftime(
                '%Y-%m-%d %H:%M:%S', 
                time.localtime(log['timestamp'])
            )
        
        return logs
    
    def add_email_template(self, name: str, subject: str, body: str) -> None:
        """添加邮件模板（简化接口）"""
        self._template.add_template(name, subject, body)
        print(f"EmailFacade: Template '{name}' added successfully")
    
    def clear_email_logs(self) -> None:
        """清空邮件日志（简化接口）"""
        self._logger.clear_logs()
        print("EmailFacade: Email logs cleared")


# ============================================================================
# 4. 演示函数
# ============================================================================

def demonstrate_computer_facade():
    """
    演示计算机外观模式
    """
    print("\n=== 计算机外观模式演示 ===")
    
    # 创建计算机外观
    computer = ComputerFacade()
    
    print("\n=== 启动计算机 ===")
    computer.start_computer()
    
    # 检查系统状态
    print("\n=== 系统状态 ===")
    status = computer.get_system_status()
    print(f"计算机运行状态: {status['computer_running']}")
    print(f"CPU状态: {status['cpu']}")
    print(f"内存状态: {status['memory']}")
    
    # 运行程序
    print("\n=== 运行程序 ===")
    computer.run_program("TextEditor", memory_mb=150, storage_mb=80)
    computer.run_program("WebBrowser", memory_mb=300, storage_mb=120)
    
    # 安装软件
    print("\n=== 安装软件 ===")
    computer.install_software("PhotoEditor", size_mb=500)
    
    # 备份数据
    print("\n=== 备份数据 ===")
    computer.backup_data("daily_backup_2024")
    
    # 停止程序
    print("\n=== 停止程序 ===")
    computer.stop_program("TextEditor")
    
    # 最终状态
    print("\n=== 最终系统状态 ===")
    final_status = computer.get_system_status()
    print(f"内存使用: {final_status['memory']['used_mb']}MB")
    print(f"存储使用: {final_status['storage']['used_gb']}GB")
    
    # 关闭计算机
    computer.shutdown_computer()


def demonstrate_database_facade():
    """
    演示数据库外观模式
    """
    print("\n=== 数据库外观模式演示 ===")
    
    # 创建数据库外观
    db = DatabaseFacade()
    
    # 连接数据库
    print("\n=== 连接数据库 ===")
    if not db.connect():
        print("数据库连接失败")
        return
    
    # 创建用户表
    print("\n=== 创建用户表 ===")
    db.create_user_table()
    
    # 添加用户
    print("\n=== 添加用户 ===")
    db.add_user("张三", "zhangsan@example.com", "13800138000")
    db.add_user("李四", "lisi@example.com", "13900139000")
    db.add_user("王五", "wangwu@example.com")
    
    # 尝试添加无效用户
    print("\n=== 添加无效用户测试 ===")
    db.add_user("无效用户", "invalid-email", "invalid-phone")
    
    # 查询用户
    print("\n=== 查询用户 ===")
    user = db.get_user_by_email("zhangsan@example.com")
    if user:
        print(f"找到用户: {user['name']} ({user['email']})")
    
    # 获取所有用户
    print("\n=== 获取所有用户 ===")
    all_users = db.get_all_users()
    for user in all_users:
        print(f"用户: {user['name']} - {user['email']}")
    
    # 搜索用户
    print("\n=== 搜索用户 ===")
    search_results = db.search_users("张")
    print(f"搜索结果: {len(search_results)} 个用户")
    
    # 更新用户
    print("\n=== 更新用户 ===")
    if all_users:
        user_id = all_users[0]['id']
        db.update_user(user_id, phone="13700137000")
    
    # 获取用户统计
    print("\n=== 用户统计 ===")
    count = db.get_user_count()
    print(f"总用户数: {count}")
    
    # 缓存统计
    print("\n=== 缓存统计 ===")
    cache_stats = db.get_cache_stats()
    print(f"缓存统计: {cache_stats}")
    
    # 删除用户
    print("\n=== 删除用户 ===")
    if all_users:
        user_id = all_users[-1]['id']
        db.delete_user(user_id)
    
    # 断开连接
    db.disconnect()


def demonstrate_email_facade():
    """
    演示邮件系统外观模式
    """
    print("\n=== 邮件系统外观模式演示 ===")
    
    # 创建邮件外观
    email_system = EmailFacade()
    
    # 设置邮件服务器
    print("\n=== 设置邮件服务器 ===")
    email_system.setup_email_server(
        smtp_server="smtp.example.com",
        smtp_port=587,
        username="noreply@example.com",
        password="password123"
    )
    
    # 发送欢迎邮件
    print("\n=== 发送欢迎邮件 ===")
    email_system.send_welcome_email(
        user_name="张三",
        user_email="zhangsan@example.com",
        company_name="科技公司"
    )
    
    # 发送密码重置邮件
    print("\n=== 发送密码重置邮件 ===")
    email_system.send_password_reset_email(
        user_name="李四",
        user_email="lisi@example.com",
        reset_link="https://example.com/reset?token=abc123"
    )
    
    # 发送通知邮件
    print("\n=== 发送通知邮件 ===")
    email_system.send_notification_email(
        user_name="王五",
        user_email="wangwu@example.com",
        notification_type="系统维护",
        message="系统将于今晚22:00-24:00进行维护，期间服务可能中断。"
    )
    
    # 发送自定义邮件
    print("\n=== 发送自定义邮件 ===")
    email_system.send_custom_email(
        to_email="admin@example.com",
        subject="测试邮件",
        body="这是一封测试邮件，用于验证邮件系统功能。"
    )
    
    # 批量发送通知
    print("\n=== 批量发送通知 ===")
    recipients = [
        "user1@example.com",
        "user2@example.com",
        "user3@example.com"
    ]
    
    results = email_system.send_bulk_notification(
        recipients=recipients,
        notification_type="重要公告",
        message="我们的服务已升级，请查看新功能介绍。"
    )
    print(f"批量发送结果: {results}")
    
    # 添加自定义模板
    print("\n=== 添加自定义模板 ===")
    email_system.add_email_template(
        name="birthday",
        subject="生日快乐，{user_name}！",
        body="亲爱的 {user_name}，\n\n祝您生日快乐！\n\n{company_name} 团队"
    )
    
    # 获取邮件统计
    print("\n=== 邮件统计 ===")
    stats = email_system.get_email_stats()
    print(f"发送统计: {stats['sender_stats']}")
    print(f"日志统计: {stats['log_stats']}")
    print(f"可用模板: {stats['available_templates']}")
    
    # 获取最近的邮件日志
    print("\n=== 最近的邮件日志 ===")
    recent_logs = email_system.get_recent_email_logs(5)
    for log in recent_logs:
        print(f"{log['formatted_time']} - {log['to_email']} - {log['status']}")


def demonstrate_performance_comparison():
    """
    演示外观模式的性能对比
    """
    print("\n=== 外观模式性能对比 ===")
    
    # 测试直接使用子系统 vs 使用外观
    import time
    
    print("\n=== 直接使用子系统 ===")
    start_time = time.time()
    
    # 直接操作各个子系统
    cpu = CPU()
    memory = Memory()
    storage = Storage()
    network = Network()
    
    # 手动启动各个子系统
    cpu.start()
    memory.initialize()
    storage.mount()
    network.connect()
    
    # 手动运行程序
    memory.allocate(100, "TestApp")
    storage.write_file("TestApp.exe", 50)
    cpu.execute("run TestApp")
    network.send_data("App started", "server")
    
    # 手动清理
    memory.deallocate("TestApp")
    storage.delete_file("TestApp.exe")
    network.disconnect()
    storage.unmount()
    memory.cleanup()
    cpu.stop()
    
    direct_time = time.time() - start_time
    print(f"直接使用子系统耗时: {direct_time:.4f}秒")
    
    print("\n=== 使用外观模式 ===")
    start_time = time.time()
    
    # 使用外观模式
    computer = ComputerFacade()
    computer.start_computer()
    computer.run_program("TestApp", 100, 50)
    computer.stop_program("TestApp")
    computer.shutdown_computer()
    
    facade_time = time.time() - start_time
    print(f"使用外观模式耗时: {facade_time:.4f}秒")
    
    print(f"\n性能对比:")
    print(f"- 直接使用: {direct_time:.4f}秒")
    print(f"- 外观模式: {facade_time:.4f}秒")
    print(f"- 外观模式开销: {((facade_time - direct_time) / direct_time * 100):.2f}%")
    
    print("\n优势分析:")
    print("- 外观模式虽然有轻微性能开销，但提供了:")
    print("  1. 简化的接口")
    print("  2. 错误处理")
    print("  3. 统一的操作流程")
    print("  4. 更好的可维护性")


def demonstrate_java_comparison():
    """
    演示与Java外观模式的对比
    """
    print("\n=== Python vs Java 外观模式对比 ===")
    
    print("\n=== Java外观模式特点 ===")
    print("""
    // Java外观模式实现
    public class ComputerFacade {
        private CPU cpu;
        private Memory memory;
        private Storage storage;
        
        public ComputerFacade() {
            this.cpu = new CPU();
            this.memory = new Memory();
            this.storage = new Storage();
        }
        
        public void startComputer() {
            cpu.start();
            memory.initialize();
            storage.mount();
        }
        
        public void shutdownComputer() {
            storage.unmount();
            memory.cleanup();
            cpu.stop();
        }
    }
    """)
    
    print("\n=== Python外观模式优势 ===")
    print("1. 动态特性:")
    print("   - 可以动态添加和移除子系统")
    print("   - 运行时修改外观行为")
    
    print("\n2. 装饰器支持:")
    print("   - 可以使用装饰器增强外观方法")
    print("   - 自动日志记录、性能监控等")
    
    print("\n3. 上下文管理器:")
    print("   - 支持with语句自动资源管理")
    print("   - 自动清理和异常处理")
    
    print("\n4. 鸭子类型:")
    print("   - 不需要严格的接口定义")
    print("   - 更灵活的子系统集成")
    
    # 演示Python特有的外观模式实现
    print("\n=== Python特有实现演示 ===")
    
    # 装饰器外观
    def log_operation(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"开始执行: {func.__name__}")
            result = func(*args, **kwargs)
            print(f"完成执行: {func.__name__}")
            return result
        return wrapper
    
    class EnhancedComputerFacade(ComputerFacade):
        @log_operation
        def start_computer(self):
            super().start_computer()
        
        @log_operation
        def shutdown_computer(self):
            super().shutdown_computer()
    
    print("\n使用装饰器增强的外观:")
    enhanced_computer = EnhancedComputerFacade()
    enhanced_computer.start_computer()
    enhanced_computer.shutdown_computer()
    
    # 上下文管理器外观
    @contextmanager
    def computer_session():
        computer = ComputerFacade()
        try:
            computer.start_computer()
            yield computer
        finally:
            computer.shutdown_computer()
    
    print("\n使用上下文管理器的外观:")
    with computer_session() as computer:
        computer.run_program("ContextApp", 50, 25)


def main():
    """
    主函数：演示外观模式的各种实现
    """
    print("外观模式 (Facade Pattern) - Python实现详解")
    print("=" * 50)
    
    # 演示各种外观模式实现
    demonstrate_computer_facade()
    demonstrate_database_facade()
    demonstrate_email_facade()
    
    # 性能对比
    demonstrate_performance_comparison()
    
    # Java对比
    demonstrate_java_comparison()
    
    print("\n=== 外观模式总结 ===")
    print("""
    外观模式核心思想:
    1. 为复杂子系统提供简化接口
    2. 隐藏子系统的复杂性
    3. 降低客户端与子系统的耦合
    4. 提供统一的访问入口
    
    Python实现特点:
    1. 利用Python的动态特性实现灵活的外观
    2. 使用装饰器增强外观功能
    3. 支持上下文管理器的资源管理
    4. 鸭子类型简化接口定义
    
    适用场景:
    1. 复杂系统的简化接口
    2. 遗留系统的现代化包装
    3. 第三方库的统一接口
    4. 微服务的API网关
    5. 数据库操作的简化
    """)


if __name__ == "__main__":
    main()